﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using ClassLibrary.DAO;
using ClassLibrary.Data;
using ClassLibrary.Entity;
using System.Globalization;

public partial class UserControl_WebUserControl : System.Web.UI.UserControl
{
    TblCustomersDAO CustomersDAO = new TblCustomersDAO(Global.CONNECTION_STRING);
    TblBookingDAO bookDAO = new TblBookingDAO(Global.CONNECTION_STRING);

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            LoadSuburb();
            txtFName.Focus();
            string id = Request.QueryString["id"];

            if (Request.QueryString["id"] == null)
            {
                btnsavenew.Visible = true;
                btnSave.Visible = false;
            }
            else
            {
                btnsavenew.Visible = true;
                if (Session[Global.SESSION_LOGGED_USER] == null)
                {
                    btNewCustomer.Enabled = false;
                    btnsavenew.Visible = false;
                    //btnSave.Visible = true;

                }
                else if (Session[Global.SESSION_LOGGED_USER] != null && (((TblCustomers)Session[Global.SESSION_LOGGED_USER]).IsAdmin == false) && id != null)
                {
                    btNewCustomer.Enabled = false;
                    //loadCustomer_Index();
                    txtPass.Enabled = false;
                    lbpass.Enabled = false;
                    txtEmail.Enabled = false;
                    loadCustomerDetail();
                    btnsavenew.Visible = false;
                    //loadJob();
                }

                if (Session[Global.SESSION_LOGGED_USER] != null && ((TblCustomers)Session[Global.SESSION_LOGGED_USER]).IsAdmin == true && id != null)
                {
                    loadJob();
                    btNewCustomer.Enabled = true;
                 
                    txtPass.Enabled = false;
                    lbpass.Enabled = false;
                    txtEmail.Enabled = false;
                    loadCustomerDetail();
                    btnsavenew.Visible = false;
                    LoadCashPurchase();
                }
            }
            
            if (id == null)
            {
                btnNewBookIn.Enabled = false;
                btnNewPurchase.Enabled = false;
            }
            else
            {
                btnNewBookIn.Enabled = true;
                btnNewPurchase.Enabled = true;
            }
        }
    }
    /*  private void loadCustomer_Index()
      {
           int id = ((TblCustomers)Session[Global.SESSION_LOGGED_USER]).CustomerIndex;
          //int id = Global.ConvertToInt(Request.QueryString["id"]);
        
          DataTable dt = CustomersDAO.GetCustomerId(id);

          foreach (DataRow customerdt in dt.Rows)
          {
              txtCompany.Text = customerdt["Companyname"].ToString();
              txtEmail.Text = customerdt["emailaddress"].ToString();
              drTitle.SelectedValue = customerdt["CustomerTitle"].ToString();
              txtFName.Text = customerdt["CustomerFirstname"].ToString();
              txtLName.Text = customerdt["CustomerLastname"].ToString();
              txtMobile.Text = customerdt["phonemobile"].ToString();
              txtNumber.Text = customerdt["postalnumber"].ToString();
              // txtPass.Enabled = false;
              txtPostcode.Text = customerdt["postalpostcode"].ToString();
              txtStreet.Text = customerdt["postalstreet"].ToString();
              // txtUsername.Text = customerdt["CustomerUsername"].ToString();
              txtWorkPhone.Text = customerdt["phonework"].ToString();
              txtFax.Text = customerdt["phonefacsimile"].ToString();
              txtHomePhone.Text = customerdt["phonehome"].ToString();
            
              if (customerdt["postalstate"].ToString() == "")
              {
                  drState.SelectedValue = "";
              }
              else
              {
                  drState.SelectedValue = customerdt["postalstate"].ToString();
              }


              if (customerdt["postalsuburb"].ToString() == "")
              {
                  drSuburb.SelectedValue = "";
              }
              else
              {
                  drSuburb.SelectedValue = customerdt["postalsuburb"].ToString();
              }
            
          }
      }
     * 
     */
    private void loadCustomerDetail()
    {
        // int id = ((TblCustomers)Session[Global.SESSION_LOGGED_USER]).CustomerIndex;
        int id = Global.ConvertToInt(Request.QueryString["id"]);

        TblCustomers customer = CustomersDAO.CustomerById(id);
        txtCustomerIndex.Text = customer.CustomerIndex.ToString();
        txtCompany.Text = customer.Companyname;
        txtEmail.Text = customer.Emailaddress;
        drTitle.SelectedValue = customer.CustomerTitle;
        txtFName.Text = customer.CustomerFirstname;
        txtLName.Text = customer.CustomerLastname;
        txtMobile.Text = customer.Phonemobile;
        txtNumber.Text = customer.Postalnumber;
        // txtPass.Enabled = false;
        txtPostcode.Text = customer.Postalpostcode;
     
        txtStreet.Text = customer.Postalstreet;
        // txtUsername.Text = customerdt["CustomerUsername"].ToString();
        txtWorkPhone.Text = customer.Phonework;
        txtFax.Text = customer.Phonefacsimile;
        txtHomePhone.Text = customer.Phonehome;
        if (customer.Postalstate == "")
        {
            drState.SelectedValue = "";
        }
        else
        {
            if (customer.Postalstate == "ACT")
            {
                ListItem lstItem = new ListItem("ACT", "");
                drState.Items.Insert(0, lstItem);
            }
            if (customer.Postalstate == "NSW")
            {

                ListItem lstItem = new ListItem("NSW", "");
                drState.Items.Insert(0, lstItem);
            }
            if (customer.Postalstate == "NT")
            {

                ListItem lstItem = new ListItem("NT", "");
                drState.Items.Insert(0, lstItem);
            }
            if (customer.Postalstate == "QLD")
            {
                ListItem lstItem = new ListItem("QL", "");
                drState.Items.Insert(0, lstItem);
            }
            if (customer.Postalstate == "SA")
            {

                ListItem lstItem = new ListItem("SA", "");
                drState.Items.Insert(0, lstItem);
            }
            if (customer.Postalstate == "TAS")
            {

                ListItem lstItem = new ListItem("Tasmania", "");
                drState.Items.Insert(0, lstItem);
            }
            if (customer.Postalstate == "VIC")
            {

                ListItem lstItem = new ListItem("VIC", "");
                drState.Items.Insert(0, lstItem);
            }
            if (customer.Postalstate == "WA")
            {
                ListItem lstItem = new ListItem("WA", "");
                drState.Items.Insert(0, lstItem);
            }
        }
        if (customer.Postalsuburb == "")
        {
            drSuburb.SelectedValue = "";
        }
        else
        {
            LoadSuburb();
            drSuburb.Text = customer.Postalsuburb;
        }
        Session[Global.SESSION_CUSTOMERS] = customer;

    }

    private void LoadSuburb()
    {
        drSuburb.DataSource = CustomersDAO.GetSuburb_All();
        drSuburb.DataTextField = "suburb";
        drSuburb.DataValueField = "suburb";
        drSuburb.DataBind();
    }
    private void LoadState()
    {
        drState.DataSource = CustomersDAO.GetState_BySuburb(drSuburb.SelectedValue, txtPostcode.Text.Trim());
        drState.DataTextField = "state";
        drState.DataValueField = "state";
        drState.DataBind();
    }
    protected void txtPostcode_TextChanged(object sender, EventArgs e)
    {
        LoadState();
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        bool flag = false;
        try
        {
            TblCustomers customer = new TblCustomers();

            customer.CustomerTitle = drTitle.SelectedValue;
            customer.CustomerFirstname = txtFName.Text;
            customer.CustomerLastname = txtLName.Text;
            customer.CustomerFullname = drTitle.SelectedValue + " " + txtFName.Text + " " + txtLName.Text;
            customer.Companyname = txtCompany.Text;
            customer.Postalnumber = txtNumber.Text;
            customer.Postalstreet = txtStreet.Text;
            if (drSuburb.SelectedValue == "")
            {

            }
            else
            {
                customer.Postalsuburb = drSuburb.SelectedItem.Text;
            }

            customer.Postalpostcode = txtPostcode.Text;
            customer.Postalstate = drState.SelectedValue;
            customer.Phonework = txtWorkPhone.Text;
            customer.Phonehome = txtHomePhone.Text;
            customer.Phonemobile = txtMobile.Text;
            customer.Phonefacsimile = txtFax.Text;
            customer.Emailaddress = txtEmail.Text;
            //customer.CustomerUsername = txtUsername.Text;
            customer.Emailpassword = Encryption.EncryptToString(txtPass.Text);
            customer.PreferContactMethod = Convert.ToInt32(drPreConMeth.SelectedValue);
            customer.DateCreated = DateTime.Now;

            string id = Request.QueryString["id"];

            DataTable DT_Customer = null;
            if (id == null || id == "" )
            {
                customer.CustomerIndex = 0;
                DT_Customer = CustomersDAO.InsUpdCustomers(customer, 1);
                foreach (DataRow dr in DT_Customer.Rows)
                {
                    txtCustomerIndex.Text = dr["CustomerIndex"].ToString();
                }
            }

            else
            {
                customer.CustomerIndex = Global.ConvertToInt(id);
                CustomersDAO.InsUpdCustomers(customer, 2);
            }
            flag = true;
        }
        catch (Exception ex)
        {
            Session[Global.SESSION_ERROR] = ex;
            Response.Redirect(Global.ERROR_PAGE);
        }
        if (flag)
        {
            //lblResult.Text = "successful";
            message_green.Style.Value = "inline";
            Response.Redirect("~/Admin/Customer.aspx?id=" + txtCustomerIndex.Text);
        }

    }

    protected void btnNewBookIn_Click(object sender, EventArgs e)
    {
       // Response.Redirect("~/Admin/Booking.aspx");
        // Khi chọn new BookIn -> link tới trang Booking với cái khách hàng vừa nhập
        Response.Redirect("~/Admin/Booking.aspx?idC=" + txtCustomerIndex.Text);
    }

    private void loadJob()
    {
        // string ID = "";
        try
        {
            int id = Global.ConvertToInt(Request.QueryString["id"]);
            TblJobsDAO jobDAO = new TblJobsDAO(Global.CONNECTION_STRING);
            grdJobList.DataSource = jobDAO.GetJobByCustomerID(id);
            grdJobList.DataBind();
        }
        catch (Exception ex)
        {
            Session[Global.SESSION_ERROR] = ex;
            Response.Redirect(Global.ERROR_PAGE);
        }
    }

    protected void grdJobList_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            //Label lb_ApprovalStatus = (Label)e.Row.Cells[5].FindControl("lbApprovalStatus");
            //int AppStatus = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "ApprovalStatus"));
            //if (AppStatus == 1)
            //    lb_ApprovalStatus.Text = " Approved ";
            //else if (AppStatus == 2)
            //    lb_ApprovalStatus.Text = " Pending Approval";
            //else
            //    lb_ApprovalStatus.Text = " Quote Rejected Approval";

            //Label lb_QuotationStatus = (Label)e.Row.Cells[6].FindControl("lbQuotationStatus");
            //int QuotaStatus = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "QuotationStatus"));

            //if (QuotaStatus == 1)
            //    lb_QuotationStatus.Text = "Quoted";
            //else if (QuotaStatus == 2)
            //    lb_QuotationStatus.Text = "Waiting for quote";
            //else
            //    lb_QuotationStatus.Text = "BER";
        }
    }
   
    protected void btNewCustomer_Click(object sender, EventArgs e)
    {

        btNewCustomer.Enabled = false;
        txtCompany.Text = string.Empty;
        txtEmail.Text = string.Empty;
        txtEmail.Enabled = true;
        txtFax.Text = string.Empty;
        txtFName.Text = string.Empty;
        txtHomePhone.Text = string.Empty;
        txtLName.Text = string.Empty;
        txtMobile.Text = string.Empty;
        txtNumber.Text = string.Empty;
        txtPass.Text = string.Empty;
        txtPass.Enabled = true;
        txtPostcode.Text = string.Empty;
        txtStreet.Text = string.Empty;
        txtWorkPhone.Text = string.Empty;

        btnsavenew.Visible = true;
        btnSave.Visible = false;


    }
    protected void btnsavenew_Click(object sender, EventArgs e)
    {
        bool flag = false;
        try
        {
            TblCustomers customer = new TblCustomers();

            customer.CustomerTitle = drTitle.SelectedValue;
            customer.CustomerFirstname = txtFName.Text;
            customer.CustomerLastname = txtLName.Text;
            customer.CustomerFullname = drTitle.SelectedValue + " " + txtFName.Text + " " + txtLName.Text;
            customer.Companyname = txtCompany.Text;
            customer.Postalnumber = txtNumber.Text;
            customer.Postalstreet = txtStreet.Text;
            // customer.Postalsuburb = drSuburb.SelectedItem.Text;
            //customer.Postalpostcode = txtPostcode.Text;
            customer.Postalpostcode = txtPostcode.Text;
            customer.Postalstate = drState.SelectedValue;
            if (drSuburb.SelectedValue == "")
            {

            }
            else
            {
                customer.Postalsuburb = drSuburb.SelectedItem.Text;
            }
            customer.Phonework = txtWorkPhone.Text;
            customer.Phonehome = txtHomePhone.Text;
            customer.Phonemobile = txtMobile.Text;
            customer.Phonefacsimile = txtFax.Text;
            customer.Emailaddress = txtEmail.Text;
            //customer.CustomerUsername = txtUsername.Text;
            customer.Emailpassword = Encryption.EncryptToString(txtPass.Text);
            customer.PreferContactMethod = Convert.ToInt32(drPreConMeth.SelectedValue);
            customer.DateCreated = DateTime.Now;

          
            DataTable DT_Customer = null;
            if (Session[Global.SESSION_LOGGED_USER] != null && (((TblCustomers)Session[Global.SESSION_LOGGED_USER]).IsAdmin == true))
            {
                customer.CustomerIndex = 0;
                DT_Customer = CustomersDAO.InsUpdCustomers(customer, 1);
                foreach (DataRow dr in DT_Customer.Rows)
                {
                    txtCustomerIndex.Text = dr["CustomerIndex"].ToString();
                }
            }
           

            flag = true;
        }
        catch (Exception ex)
        {
            Session[Global.SESSION_ERROR] = ex;
            Response.Redirect(Global.ERROR_PAGE);
        }
        if (flag)
        {
            //lblResult.Text = "successful";
            message_green.Style.Value = "inline";
            Response.Redirect("~/Admin/Customer.aspx?id=" + txtCustomerIndex.Text);
        }

    }
    protected void txtFName_TextChanged(object sender, EventArgs e)
    {
        txtFName.Text = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(txtFName.Text);
    }
    protected void txtLName_TextChanged(object sender, EventArgs e)
    {
        txtLName.Text = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(txtLName.Text);
    }
    protected void txtCompany_TextChanged(object sender, EventArgs e)
    {
        txtCompany.Text = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(txtCompany.Text);
    }
    protected void txtStreet_TextChanged(object sender, EventArgs e)
    {
        txtStreet.Text = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(txtStreet.Text);
    }

    protected void drSuburb_SelectedIndexChanged(object sender, EventArgs e)
    {
        DataTable dt = CustomersDAO.GetPostcode_ByState(drSuburb.SelectedValue);
        foreach (DataRow dr in dt.Rows)
        {
            txtPostcode.Text = dr["postcode"].ToString();
            LoadState();
        }
    }
    //load purchase

    private void LoadCashPurchase()
    {
        string id = Request.QueryString["id"];
        // noi dung booking
        DataTable dt = bookDAO.GetBookingByCus(Global.ConvertToInt(id));

        grdOrder.DataSource = dt;
        grdOrder.DataBind();      

    }

    protected void btnNewPurchase_Click(object sender, EventArgs e)
    {
    
    }
  
}
